package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Follow;
import com.hmdp.mapper.FollowMapper;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IFollowService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements IFollowService {

    @Autowired
    private FollowMapper followMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private IUserService userService;

    /**
     * 关注或取关
     * @param id   要关注的博主id
     * @param isFollow   true，则为关注操作
     * @return
     */
    @Override
    public Result follow(Long id, Boolean isFollow) {
        Long userId = UserHolder.getUser().getId(); //当前用户id
        String key = RedisConstants.BLOG_FOLLOW_KEY + userId;

        //判断是否为关注操作
        if (isFollow) {
            //关注操作，添加数据到数据库中
            Follow follow = new Follow();
            follow.setFollowUserId(id);
            follow.setUserId(userId);
            boolean isSuccess = save(follow);
            if (isSuccess){
                //同时将信息存入redis，以当前用户id为key，存储关注的博主id
                redisTemplate.opsForSet().add(key, id.toString());
            }
        }

        //取关操作，从表中删除数据
        else {
            followMapper.deleteWithFollowerAndBloger(id, userId);
            //取关成功，将博主信息移除
            redisTemplate.opsForSet().remove(key, id.toString());
        }

        return Result.ok();
    }


    /**
     * 判断当前用户是否关注博主
     * @param id  博主id
     * @return
     */
    @Override
    public Result isFollow(Long id) {
        Long userId = UserHolder.getUser().getId();

        Integer count = query().
                eq("user_id", userId).
                eq("follow_user_id", id).
                count();

        //若关注信息=0，说明未关注，返回false
        return Result.ok(count > 0);
    }


    /**
     * 查看当前博主与用户的共同关注
     * @param id  当前博主id
     * @return
     */
    @Override
    public Result commonFollow(Long id) {
        Long userId = UserHolder.getUser().getId();
        String userKey = RedisConstants.BLOG_FOLLOW_KEY + userId;   //当前用户的redis查询key
        String bloggerKey = RedisConstants.BLOG_FOLLOW_KEY + id;    //当前博主的redis查询key

        //查询两个集合的交集
        Set<String> commonIds = redisTemplate.opsForSet().intersect(userKey, bloggerKey);

        //转为UserDTO对象
        List<UserDTO> commonUsers = commonIds.stream().map(
                commonId -> BeanUtil.copyProperties(userService.getById(Integer.parseInt(commonId)), UserDTO.class)
        ).collect(Collectors.toList());

        return Result.ok(commonUsers);
    }
}
